<template>
  <div class="payment-page">
    <!-- 返回按钮 -->
    <el-button
      style="
        background-color: #409eff;
        color: white;
        font-weight: 700;
        margin: 10px 0 20px 10px;
      "
      @click="goBack"
      class="back-button"
    >
      <el-icon><DArrowLeft /></el-icon>
      {{ $t("payment.back") }}
    </el-button>
    <!-- 确认收货地址部分 -->
    <div class="address-section">
      <div class="address-header">
        <h3>{{ $t("payment.confirm_shipping_address") }}</h3>
        <span class="separator"></span>
        <span @click="GoToLocations" class="manage-address">{{
          $t("payment.manage_address")
        }}</span>
      </div>
      <el-card
        v-for="(address, index) in displayedAddresses"
        :key="index"
        class="address-item"
        :class="{ selected: selectedAddressIndex === index }"
        @click="selectAddress(index)"
      >
        <el-icon
          v-if="address.isDefault === 1"
          :class="[
            'default-icon',
            { 'selected-icon': selectedAddressIndex === index },
          ]"
        >
          <LocationInformation />
        </el-icon>
        <el-icon
          v-else
          :class="[
            'normal-icon',
            { 'selected-icon': selectedAddressIndex === index },
          ]"
        >
          <Location />
        </el-icon>
        <span v-if="address.isDefault === 1" class="default-text">{{
          $t("payment.default")
        }}</span>
        <h2
          :title="`${address.province} ${address.city} ${address.district} ${address.streetAddress}`"
        >
          {{ address.address }}
        </h2>
        <p>{{ address.consignee }} {{ address.phone }}</p>
      </el-card>
      <el-dropdown>
        <a href="#" class="show-all-address" @click="toggleAddressVisibility">
          {{
            isAllAddressesVisible
              ? $t("payment.collapse_all_address")
              : $t("payment.show_all_address")
          }}
          <el-icon><ArrowDown /></el-icon>
        </a>
        <template #dropdown>
          <!-- 这里后续可以添加显示全部地址的具体内容 -->
        </template>
      </el-dropdown>
    </div>

    <!-- 确认订单信息部分 -->
    <div class="order-info-section">
      <h2>{{ $t("payment.confirm_order_info") }}</h2>
      <el-table :data="products" stripe>
        <el-table-column :label="$t('payment.store_products')" width="200">
          <template #default="scope">
            <div class="product-info">
              <el-image
                style="width: 50px; height: 50px"
                :src="getProductImage(scope.row)"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="getPreviewSrcList(scope.row)"
                show-progress
                :preview-teleported="true"
                fit="cover"
                alt="商品图片"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('payment.product_name')" width="200">
          <template #default="scope" class="product-name">
            {{ scope.row.productName }}
          </template></el-table-column
        >
        <el-table-column :label="$t('payment.original_price')" width="200">
          <template #default="scope">
            ￥ {{ scope.row.productPrice }}
          </template></el-table-column
        >
        <el-table-column :label="$t('payment.quantity')" width="200">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              :disabled="isQuantitySpecified"
              @change="updateTotalPrice"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column :label="$t('payment.subtotal')" width="200">
          <template #default="scope">
            ￥ {{ formatPrice(scope.row.productPrice * scope.row.quantity) }}
          </template></el-table-column
        >
      </el-table>
    </div>

    <!-- 付款详情部分 -->
    <div class="payment-details-section">
      <div class="payment-item">
        <span>{{ $t("payment.total_product_price") }}</span>
        <h4 class="total-price">￥ {{ totalPrice }}</h4>
        <span style="margin-left: 100px">{{
          $t("payment.total_product_quantity")
        }}</span>
        <h4 class="total-stock">{{ selectedProductCount }}</h4>
      </div>
      <div class="payment-item total-row">
        <h3>{{ $t("payment.select_payment_method") }}</h3>
        <el-radio-group v-model="selectedPaymentMethod">
          <el-radio label="alipay" class="payment-radio">
            <img
              src="../../assets/img/Alipay.png"
              alt="支付宝图标"
              class="payment-icon"
            />
            {{ $t("payment.alipay") }}</el-radio
          >
          <el-radio label="wechat" alt="微信图标" class="payment-radio">
            <img src="../../assets/img/Wechat.png" class="payment-icon" />
            {{ $t("payment.wechat") }}</el-radio
          >
          <el-radio label="bankcard" class="payment-radio">
            <img
              src="../../assets/img/Bankcard.png"
              alt="银行卡图标"
              class="payment-icon"
            />
            {{ $t("payment.bankcard") }}</el-radio
          >
        </el-radio-group>
        <span>
          <el-button class="pay-button" @click="handlePayButtonClick">{{
            hasOrderId ? $t("payment.submit_order") : $t("payment.pay")
          }}</el-button>
        </span>
      </div>
    </div>
    <!-- 显示二维码图片 -->
    <el-dialog
      v-model="QRdialogVisible"
      :title="$t('payment.scan_qr_code')"
      width="500"
      class="custom-qr-dialog"
    >
      <div v-if="qrCodeBase64" class="qr-code">
        <img :src="qrCodeBase64" alt="QR Code" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="background-color: #85bcfd; color: white"
            @click="QRdialogVisible = false"
            >{{ $t("payment.payment_complete") }}</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import "../../assets/css/Payment.css";
import { ref, onMounted, computed, onUnmounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ArrowDown,
  DArrowLeft,
  Location,
  LocationInformation,
} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
// import { useStomp } from '@/utils/Stomp.js';

const userInfo = JSON.parse(localStorage.getItem("xm-pro-user"));
const buyerid = userInfo.id;

const route = useRoute();
const router = useRouter();

const orderData = JSON.parse(route.query.orderData || "{}");
const apiResponse = JSON.parse(route.query.apiResponse || "{}");
const receivedProducts = JSON.parse(route.query.products || "[]");
const products = ref(
  receivedProducts.map((product) => {
    return {
      productId: product.productId || product.id,
      productName: product.productName || product.name,
      productPrice: product.productPrice || product.unitPrice,
      quantity: product.quantity,
      imagePath: product.imagePath,
    };
  })
);
console.log("支付页面接收到的订单数据：", orderData);
console.log("支付页面接收到的 API 响应：", apiResponse);
console.log("支付页面接收到的商品数据信息：", receivedProducts);

//判断商品数量是否已指定
const isQuantitySpecified = ref(
  receivedProducts.every((product) => {
    return typeof product.quantity === "number" && product.quantity > 0;
  })
);

const QRdialogVisible = ref(false);
//选中的地址索引
const selectedAddressIndex = ref(0);
// 存储地址数据
const addresses = ref([]);
//获取用户地址
const getAllAddress = () => {
  request
    .get(`address/getAll/${buyerid}`)
    .then((res) => {
      if (res.msg === "成功") {
        addresses.value = res.data.map((addr) => {
          addr.address = `${addr.province} ${addr.city} ${addr.district} ${addr.streetAddress}`;
          return addr;
        });
        // 在数据加载完成后调用确保默认地址在第一个位置的函数
        ensureDefaultAddressFirst();
      } else {
        ElMessage({
          message: "获取地址数据失败",
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("获取地址数据失败", err);
      ElMessage({
        message: "获取地址数据失败，请稍后重试",
        type: "error",
      });
    });
};

// 选择地址
const selectAddress = (index) => {
  selectedAddressIndex.value = index;
};
// 确保默认地址在第一个位置
const ensureDefaultAddressFirst = () => {
  const defaultAddress = addresses.value.find((addr) => addr.isDefault === 1);
  if (defaultAddress) {
    const index = addresses.value.indexOf(defaultAddress);
    addresses.value.splice(index, 1);
    addresses.value.unshift(defaultAddress);
  }
};

// 控制是否显示全部地址
const isAllAddressesVisible = ref(false);
// 计算显示的地址列表
const displayedAddresses = computed(() => {
  if (isAllAddressesVisible.value || addresses.value.length <= 4) {
    return addresses.value;
  } else {
    return addresses.value.slice(0, 4);
  }
});

// 切换地址显示状态
const toggleAddressVisibility = () => {
  isAllAddressesVisible.value = !isAllAddressesVisible.value;
};

//保留两位小数
const formatPrice = (price) => {
  return Number(price).toFixed(2);
};

//获取商品第一张图片
const getProductImage = (product) => {
  if (product.imagePath && product.imagePath.length > 0) {
    const imageFiles = product.imagePath.split(";");
    return imageFiles.length > 0 ? `${imageFiles[0]}` : "";
  }
  return "";
};
//图片预览
const getPreviewSrcList = (product) => {
  if (product.imagePath && product.imagePath.length > 0) {
    return product.imagePath.split(";");
  }
  return [];
};

//计算商品总价
const totalPrice = computed(() => {
  return products.value.reduce(
    (sum, product) => sum + product.productPrice * product.quantity,
    0
  );
});
const selectedProductCount = computed(() => {
  if (!orderData.items) {
    return products.value.reduce((sum, product) => sum + product.quantity, 0);
  }
  return Object.values(orderData.items).reduce(
    (sum, quantity) => sum + quantity,
    0
  );
});

// 更新总价
const updateTotalPrice = () => {
  console.log("updateTotalPrice called");
  // 这里总价和商品数量会自动更新，因为它们是基于 products 计算的 computed 属性
};

//判断是否已经有订单ID
const hasOrderId = ref(!!orderData.orderId);
console.log("已有订单ID为1：", orderData.orderId);
console.log("已有订单ID为2：", hasOrderId.value);

//创建ref来存储WebSocket实例
// const socket = ref(null);

// 重连次数和重连间隔
// const maxReconnectAttempts = 2;
// const reconnectInterval = 3000; // 3 秒
// let reconnectAttempts = 0;

// 建立 WebSocket 连接
// const connectWebSocket = (orderId) => {
//   console.log('Connecting to WebSocket with orderId:', orderId);
//   socket.value = new WebSocket(`ws://localhost:8080/ws?orderId=${orderId}`);
//
//   socket.value.onopen = () => {
//     console.log("WebSocket 连接成功");
//     socket.value.send("Hello Server!");
//     reconnectAttempts = 0; // 连接成功后重置重连次数
//   };
//
//   socket.value.onmessage = (event) => {
//     console.log(event.data);
//     if (event.data === 'PAYMENT_SUCCESS'){
//       router.push({
//         path: 'myorder',
//         name: 'MyOrder'
//       });
//     }
//   };
//
//   socket.value.onclose = () => {
//     console.log("WebSocket 连接关闭");
//     if (reconnectAttempts < maxReconnectAttempts) {
//       reconnectAttempts++;
//       console.log(`尝试第 ${reconnectAttempts} 次重连...`);
//       setTimeout(() => connectWebSocket(orderId), reconnectInterval);
//     } else {
//       console.log("达到最大重连次数，停止重连");
//     }
//   };
//
//   socket.value.onerror = (error) => {
//     console.error("WebSocket 连接错误:", error);
//     socket.value.close(); // 关闭连接以触发重连
//   };
// };

//处理支付点击事件
const handlePayButtonClick = async () => {
  if (!selectedPaymentMethod.value) {
    ElMessageBox.alert("请选择支付方式", {
      confirmButtonText: "确认",
    });
    return;
  }
  if (selectedAddressIndex.value === -1) {
    ElMessageBox.alert("请选择收获地址", {
      confirmButtonText: "确认",
    });
    return;
  }
  console.log("已有订单ID为3：", !hasOrderId.value);
  if (!hasOrderId.value) {
    const addressId = addresses.value[selectedAddressIndex.value].id;
    const items = {};
    products.value.forEach((product) => {
      items[product.productId] = product.quantity;
    });
    const orderData = {
      buyerId: buyerid,
      items,
      adressId: addressId,
    };
    try {
      const response = await request.post("order/create", orderData);
      console.log("订单创建响应:", response); // 打印详细响应数据
      if (response && response.data) {
        // 根据实际情况判断订单是否创建成功
        if (response.data.success === true && response.data.orderId) {
          const order = response.data;
          const orderId = order.orderId;
          hasOrderId.value = true;
          await handlePayment(orderId);
          ElMessage({
            message: "订单创建成功!",
            type: "primary",
          });
        } else {
          ElMessage({
            message: "订单创建失败",
            type: "error",
          });
        }
      } else {
        ElMessage({
          // message: '订单创建失败，未获取到有效响应',
          message: "订单创建成功",
          type: "success",
        });
        // 跳转到 MyOrder 页面的待付款订单列表
        router.push({
          path: "myorder",
          name: "MyOrder",
          query: { status: "unpaid" },
        });
      }
    } catch (error) {
      console.log("订单创建请求出错", error);
      ElMessage({
        message: "订单创建请求出错，请稍后重试",
        type: "error",
      });
    }
  } else {
    //订单已存在
    await handlePayment(orderData.orderId);
  }
};

//选择支付方式
const selectedPaymentMethod = ref("");
// 创建一个 ref 来存储 Base64 编码的图片数据
const qrCodeBase64 = ref(null);
// 将 ArrayBuffer 转换为 Base64 编码字符串
function arrayBufferToBase64(buffer) {
  const binary = String.fromCharCode.apply(null, new Uint8Array(buffer));
  return window.btoa(binary);
}

// 轮询定时器
let pollingInterval;

// 支付接口
const handlePayment = async () => {
  if (!selectedPaymentMethod.value) {
    ElMessageBox.alert("请选择支付方式", {
      confirmButtonText: "确认",
    });
    return;
  }
  let payMethod;
  if (selectedPaymentMethod.value === "alipay") {
    payMethod = 1;
  } else if (selectedPaymentMethod.value === "wechat") {
    payMethod = 2;
  } else if (selectedPaymentMethod.value === "bankcard") {
    payMethod = 3;
  }

  if (selectedPaymentMethod.value === "alipay") {
    try {
      // 从 orderData 中获取实际的订单 ID
      const orderId = orderData.orderId;
      console.log("在发送请求的过程中订单ID为：", orderId);
      // 建立 WebSocket 连接
      // connectWebSocket(orderId);

      // 发送请求，获取字节数组
      const response = await request({
        url: `/pay/alipay`,
        method: "get",
        params: {
          OrderId: orderId,
          payMethod: payMethod,
        },
        responseType: "arraybuffer",
      });
      const arrayBuffer = response;

      // 将字节流转换为 Base64 编码
      qrCodeBase64.value = `data:image/png;base64,${arrayBufferToBase64(
        arrayBuffer
      )}`;
      QRdialogVisible.value = true;
    } catch (error) {
      console.error("支付请求出错:", error);
      ElMessage({
        message: "获取支付二维码失败，请稍后重试",
        type: "error",
      });
    }
  }
};

// 清除轮询定时器
onUnmounted(() => {
  // if (socket.value) {
  //   socket.value.close();
  // }
  if (pollingInterval) {
    clearInterval(pollingInterval);
  }
});

// 返回上一页
const goBack = () => {
  router.go(-1);
};

const GoToLocations = () => {
  router.push({
    path: "userlocation",
    name: "UserLocation",
    query: { needRefresh: true },
  });
};

onMounted(async () => {
  getAllAddress(); // 页面加载时获取订单数据
});
</script>
